package manager;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import utils.DBConnector;

/**
 * Servlet implementation class RemoveCourseFromDB
 */
public class RemoveUsersFromDB extends BaseCMServlet {
	private static final long serialVersionUID = 1L;
       
   
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if (request.getSession(false) == null || request.getSession(false).getAttribute("username") == null){
			response.sendError(HttpServletResponse.SC_FORBIDDEN, "Please login first");
			return;
		}
		
		if (!request.getSession(false).getAttribute("type").equals("admin")) {
			response.sendError(HttpServletResponse.SC_FORBIDDEN, "Only Admin can remove other users");
			return;			
		}
		
		DBConnector dbConn = null;
		try {
			dbConn = new DBConnector();
			
			PreparedStatement stmnt = dbConn.getConnection().prepareStatement(
						"DELETE from users " +
						"WHERE username = ? ");
	
						
						
			String[] names = request.getParameterValues("check");
			if (names == null){
				response.sendRedirect("");
				return;
			}
			
			for (String name : names){
				stmnt.setString(1, name);
				SessionManager.invalidateSession(name);
				stmnt.execute();
			}
			
			response.sendRedirect("view_users.jsp");
		
		} catch (SQLException e) {
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			try {
				dbConn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
		

}
